// articles.js - 前端文章模块

// 定义模块接口
const ArticlesModule = (() => {
    // 私有方法：创建文章元素
    const createArticleElement = (article) => {
        const articleLink = document.createElement('a');
        articleLink.href = '#';
        articleLink.classList.add('bg-white', 'rounded-xl', 'overflow-hidden', 'shadow-sm', 'card-hover');

        // 构建文章元素的代码（保持原有逻辑不变）
        const articleImage = document.createElement('img');
        articleImage.src = article.image;
        articleImage.alt = article.title;
        articleImage.classList.add('w-full', 'h-48', 'object-cover');
        articleLink.appendChild(articleImage);

        // 其余创建元素的代码...
        // （保持与原始代码相同）

        return articleLink;
    };

    // 私有方法：初始化点赞按钮
    const initLikeButtons = () => {
        const likeButtons = document.querySelectorAll('.like-btn');
        likeButtons.forEach(button => {
            button.addEventListener('click', function () {
                const itemId = this.dataset.id;
                const likeCountElement = this.querySelector('.like-count');
                const isLiked = localStorage.getItem(`liked_${itemId}`);

                if (!isLiked) {
                    let currentCount = parseInt(likeCountElement.textContent, 10);
                    currentCount++;
                    likeCountElement.textContent = currentCount;
                    this.classList.add('liked');
                    localStorage.setItem(`liked_${itemId}`, 'true');

                    // 新增：异步更新后端点赞数
                    updateLikeCount(itemId);
                }
            });
        });
    };

    // 私有方法：更新后端点赞数（新增功能）
    const updateLikeCount = async (articleId) => {
        try {
            const response = await fetch(`/api/articles/${articleId}/like`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });

            if (!response.ok) {
                throw new Error('Failed to update like count');
            }
        } catch (error) {
            console.error('Error updating like count:', error);
            // 可以添加 UI 提示用户点赞未成功
        }
    };

    // 私有方法：加载文章数据
    const loadArticles = async () => {
        const articlesContainer = document.getElementById('articles');
        if (!articlesContainer) return;

        try {
            // 从后端 API 获取真实数据
            const response = await fetch('/api/articles');
            if (!response.ok) throw new Error('Failed to fetch articles');

            const articles = await response.json();
            articlesContainer.innerHTML = ''; // 清空容器

            articles.forEach(article => {
                const articleElement = createArticleElement(article);
                articlesContainer.appendChild(articleElement);
            });
        } catch (error) {
            console.error('Error loading articles:', error);
            // 显示加载失败的 UI
            articlesContainer.innerHTML = '<p class="text-red-500">加载文章失败，请重试</p>';
        }
    };

    // 公共方法：初始化模块
    const init = () => {
        initLikeButtons();
        loadArticles();
    };

    // 暴露公共接口
    return {
        init
    };
})();

// 页面加载后初始化模块
document.addEventListener('DOMContentLoaded', ArticlesModule.init);

const express = require('express');
const router = express.Router();
const { createArticle, getMyArticles } = require('../controllers/articlesController');
const { verifyToken } = require('../middlewares/auth');

router.post('/', verifyToken, createArticle);
router.get('/my', verifyToken, getMyArticles);

module.exports = router;